"use strict";

import Vue from 'vue';
import axios from "axios";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

//axios的基本配置
let config = {
	baseURL: "http://localhost:8080/",
	timeout: 10000, // Timeout
	withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);
// const userMsg={
//     u_id:'',
//     u_name:'',
//     ro_name:'',
//     ro_status:'',
//     loginSign:''
// }
// Vue.prototype.$userMsg=userMsg;
_axios.interceptors.request.use(
	function(config) {
		// Do something before request is sent
		return config;
	},
	function(error) {
		// Do something with request error
		return Promise.reject(error);
	}
);

// Add a response interceptor
_axios.interceptors.response.use(
	function(response) {
		// Do something with response data
		let result = response.data;
		let vue = new Vue();
		// console.log(result)
		//排除请求方式中不含有login的属性，直接通过
		if (!result.hasOwnProperty("loginSign")) {
			return result;
		}
		
		//排除未登录的用户
		if (!result.loginSign) { //未登录跳转登录界面
			vue.$message({
				message: '请先登录',
				type: 'warning',
				//显示时间，毫秒
				duration: 1000,
				//文字是否居中
				center: true,
				onClose: () => {
					//跳转登录页面
					window.location.href = "/"
				}
			});
		}
		// console.log(result)
		//已登录返回结果
		return result;
	},
	function(error) {
		let vue = new Vue();
		if (error.response) {
			vue.$message({
				message: '响应错误：'+error.response.status,
				type: 'warning',
				//显示时间，毫秒
				duration: 1000,
				//文字是否居中
				center: true,
			});
			//打印错误信息
			console.log(error.response)
		} else if (error.request) {
			vue.$message({
				message: '请求未通过',
				type: 'warning',
				//显示时间，毫秒
				duration: 1000,
				//文字是否居中
				center: true,
			});
			console.log(error.request);
		} else {
			vue.$message({
				message: '网络未连接',
				type: 'error',
				//显示时间，毫秒
				duration: 1000,
				//文字是否居中
				center: true,
			});
			console.log('Error', error.message);
		}


		// Do something with response error
		return Promise.reject(error);
	}
);

Plugin.install = function(Vue, options) {
	Vue.axios = _axios;
	window.axios = _axios;
	Object.defineProperties(Vue.prototype, {
		axios: {
			get() {
				return _axios;
			}
		},
		$axios: {
			get() {
				return _axios;
			}
		},
	});
};

Vue.use(Plugin)

export default Plugin;
